package com.wy.swagger;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.core.runtime.IProgressMonitor;

import com.wy.base.AbstractWizard;
import com.wy.util.PluginUtils;

public class SwaggerWizard extends AbstractWizard {

	public static String controllerPath = null;

	public SwaggerWizard() {
		super();
		setNeedsProgressMonitor(true);
	}

	/**
	 * Adding the page to the wizard.
	 */
	@Override
	public void addPages() {
		// page = new SwaggerConfigPage(selection);
		// addPage(page);
		setPage(new SwaggerWizardPage(this.getSelection()));
		addPage(getPage());
	}

	/**
	 * This method is called when 'Finish' button is pressed in the wizard. We will
	 * create an operation and run it using wizard as execution context.
	 */
	@Override
	public boolean performFinish() {
		controllerPath = ((SwaggerWizardPage) getPage()).getControllerPath();
		return super.performFinish("/templates/SwaggerConfig.template");
	}

	@Override
	public void additionalFinish(String containerName, String fileName, String packageName, IProgressMonitor monitor,
			String templateUri) {
		PluginUtils.addPom(containerName, "io.springfox", "springfox-boot-starter", "3.0.0");
	}

	@Override
	public String loadTemplate(String containerName, String templateUri) throws Exception {
		StringBuffer sb = new StringBuffer();
		BufferedReader reader;
		InputStream input = this.getClass().getResourceAsStream(templateUri);
		reader = new BufferedReader(new InputStreamReader(input));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
			line = line.replaceAll("#classname", fileName);
			line = line.replaceAll("#package", packageName);
			line = line.replaceAll("#controllerpath", controllerPath);
			boolean skip = false;
			line = line.replaceAll("#projectname", containerName);
			if (!skip) {
				sb.append(line);
				sb.append("\n");
			}
		}
		reader.close();
		reader.close();
		return sb.toString();
	}
}